H.W.2 & H.W.3

Q1
# bisection method HW2
import numpy as np
def f(x):
return np.exp(x)*np.log(x)-x**2
if __name__=="__main__":
a=1.0
b=2.0
delta=1.0e-6
err=1.
while(err>delta):
x0=(a+b)/2
if f(a)*f(x0)<=0:
b=x0
else:
a=x0
err=np.abs(a-b)
x_=(a+b)/2
print("Solution of f(x):", x_)
Q2
# bisection method HW3
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return x**5-3*x**4-5*x**3+x**2+x+3
if __name__=="__main__":
a=-2.0
b=4.0
# before needs to plot
#x=np.linspace(a, b, 1000)
#y=f(x)
#plt.plot(x, y)
#plt.show()
# seem f(x) has two sol
# 1. a=-2, b=0
# 2. a=0, b=4
lim=[[-2, 0], [0, 4]]
sol=[]
for ran in lim:
delta=1.0e-6
err=1.
a=ran[0]; b=ran[1]
while(err>delta):
x=(a+b)/2
if f(a)*f(x)<=0:
b=x
else:
a=x
err=np.abs(a-b)
sol.append(x)
print("Solution x:", sol[0], "and", sol[1])